-importPackage(Packages["okhttp3"]);


var CONFIG = storages.create("CONFIG");
var ip = CONFIG.get("ip","172.16.176.234");

// 检查无障碍权限
auto.waitFor("normal");
events.setKeyInterceptionEnabled("volume_down", true);
threads.start(function(){
    events.observeKey();
events.on("key", function(volume_down, event){
    //处理按键事件
  //  toast("音量下键被按下了");
    log("脚本已停止运行");
    exit();
});
});


var client = new OkHttpClient.Builder().retryOnConnectionFailure(true).build();

var request = new Request.Builder().url("ws://"+ip+":9317").build();
client.dispatcher().cancelAll();//清理一次
myListener = {
    onOpen: function (webSocket, response) {
        print("onOpen");
        console.log("onOpen");
        var json = {};
        json.type="hello";
        json.data= {device_name:"模拟设备",client_version:123,app_version:123,app_version_code:"233"};
        var hello=JSON.stringify(json);
        webSocket.send(hello);
    },
    onMessage: function (webSocket, msg) {
        print("msg");
        print(msg);
        console.log(msg.type);
        if(msg.type == "command") {
            if (msg.data.command == "run") {
                console.log("执行脚本");
                console.log(msg.data.script);
            }
        }
    },
    onClosing: function (webSocket, code, reason) {
        print("正在关闭");
    },
    onClosed: function (webSocket, code, reason) {
        print("关闭");
    },
    onFailure: function (webSocket, t, response) {
        print("错误");
        print( t);
    }
}
var webSocket= client.newWebSocket(request, new WebSocketListener(myListener));

setInterval(() => {

}, 1000);